import 'package:get/get.dart';
import 'package:xmshop/app/models/user_model.dart';
import 'package:xmshop/app/modules/checkout/controllers/checkout_controller.dart';
import 'package:xmshop/app/services/httpsClient.dart';
import 'package:xmshop/app/services/signService.dart';
import 'package:xmshop/app/services/userService.dart';
import '../../../../models/address_model.dart';

class AddressListController extends GetxController {
  HttpsClient httpsClient = HttpsClient();
  CheckoutController checkoutController = Get.find<CheckoutController>();
  RxList<AddressItemModel> addressList = <AddressItemModel>[].obs;

  final count = 0.obs;
  @override
  void onInit() {
    super.onInit();
    getAddressList();
  }

  @override
  void onClose() {
    super.onClose();
    checkoutController.getDefaultAddress();
  }

  getAddressList() async {
    // 获取用户信息
    var userInfoMap = await UserService.getUserInfo();
    if (userInfoMap != null) {
      UserModel userInfo =
          UserModel.fromJson(userInfoMap as Map<String, dynamic>);
      Map tempJson = {"uid": userInfo.sId};
      String sign = SignService.getSign({...tempJson, "salt": userInfo.salt});

      var response = await httpsClient
          .get("api/addressList?uid=${userInfo.sId}&sign=$sign");
      if (response != null) {
        var tempAddressList = AddressModel.fromJson(response.data);
        addressList.value = tempAddressList.result!;
        update();
      }
    }
  }

  changeDefaultAddress(id) async {
    var userInfoMap = await UserService.getUserInfo();
    if (userInfoMap != null) {
      UserModel userInfo =
          UserModel.fromJson(userInfoMap as Map<String, dynamic>);
      Map tempJson = {"uid": userInfo.sId, "id": id};
      String sign = SignService.getSign({...tempJson, "salt": userInfo.salt});

      var response = await httpsClient
          .post("api/changeDefaultAddress", data: {...tempJson, "sign": sign});
      if (response != null) {
        // 返回到结算页
        Get.back();
      }
    }
  }

  // 删除收货地址
  deleteAddress(id) async {
    var userInfoMap = await UserService.getUserInfo();
    if (userInfoMap != null) {
      UserModel userInfo =
          UserModel.fromJson(userInfoMap as Map<String, dynamic>);
      Map tempJson = {"uid": userInfo.sId, "id": id};
      String sign = SignService.getSign({...tempJson, "salt": userInfo.salt});

      var response = await httpsClient
          .post("api/deleteAddress", data: {...tempJson, "sign": sign});
      if (response != null) {
        //删除成功重新更新当前页面的数据
        getAddressList();
      }
    }
  }
}
